package com.ruoyi.web.controller.app.api.controller;

import com.ruoyi.applet.appletRegion.domain.AppletRegion;
import com.ruoyi.applet.appletRegion.domain.Region;
import com.ruoyi.applet.appletRegion.service.IAppletRegionService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 地区接口
 * @author ruoyi
 * @date 2024-12-17
 */
@RestController
@RequestMapping("/wxApi/region")
public class RegionAppletController extends BaseController {
    
    @Resource
    private IAppletRegionService appletRegionService;
    
    /**
     * 查询省市县列表
     */
    @PostMapping("/getRegionList")
    public AjaxResult getRegionList() {
        AppletRegion appletRegion = new AppletRegion();
        appletRegion.setId(null);
        appletRegion.setPid(null);
        appletRegion.setDeep(null);
        appletRegion.setName(null);
        appletRegion.setExtId(null);
        appletRegion.setExtName(null);
        appletRegion.setStatus(null);
        appletRegion.setSunList(null);
        
        
        appletRegion.setStatus(1L);
        List<AppletRegion> list = appletRegionService.selectAppletRegionList(appletRegion);
        
        List<AppletRegion> date = new ArrayList<>();
        for (AppletRegion region : list) {
            if (region.getStatus() == 1) {
                if (region.getPid() == 0) {
                    date.add(region);
                }
                for (AppletRegion cityDistrict : list) {
                    if (region.getId().equals(cityDistrict.getPid())) {
                        region.getSunList().add(cityDistrict);
                    }
                }
            }
        }
        
        List<Region> dateList = new ArrayList<>();
        for (AppletRegion i : date) {
            Region region = new Region(i);
            region.setChildren(getChildren(i));
            dateList.add(region);
        }
        return AjaxResult.success(dateList);
    }
    
    public List<Region> getChildren(AppletRegion appletRegion) {
        if (appletRegion.getSunList() == null || appletRegion.getSunList().isEmpty()) {
            return null;
        }
        List<Region> dateList = new ArrayList<>();
        for (AppletRegion i : appletRegion.getSunList()) {
            Region region = new Region(i);
            region.setChildren(getChildren(i));
            dateList.add(region);
        }
        return dateList;
    }
}
